#!/usr/bin/env python
# -*- coding: utf-8 -*-

# forever mako

import threading,time

class CommandManager:
    def __init__(self):
        self.lock = threading.Lock()
        self.ExceFunction={}
        self.CommandStr=""
        self.Reading=False
        self.DefaultFunc=None
        
        
    def Run(self):
        self.Reading=True
        t=threading.Thread(target=self.ReadCommand)
        t.start()  
    
    def Stop(self):
        self.Reading=False
        
    
    def RegisterCommand(self,cmd,func):
        if not self.ExceFunction.has_key(cmd):
            self.ExceFunction[cmd]=[]
        if self.ExceFunction[cmd].count(func)==0:
            self.ExceFunction[cmd].append(func)
            
    def RegisterDefaultCommand(self,func):
        self.DefaultFunc=func
            
    def Excute(self):
        self.lock.acquire()
        cmd=self.CommandStr
        self.lock.release()  
        if cmd!="":
            self.ExecCommand(cmd)            
            self.lock.acquire()
            self.CommandStr=""
            self.lock.release()        
        
    def ExecCommand(self,CommandWithParam):
        cmds=CommandWithParam.split(' ')
        print(cmds)
        if self.ExceFunction.has_key(cmds[0]):
            for func in self.ExceFunction[cmds[0]]:
                try:
                    func(CommandWithParam)
                except Exception as  e:
                    print(e)
        elif self.DefaultFunc:
            try:
                self.DefaultFunc(CommandWithParam)
            except Exception as e:
                print(e)
                
    def ReadCommand(self):
        while self.Reading:
            cmd = raw_input()     
            if cmd.lstrip()!='':   
                self.lock.acquire()
                self.CommandStr=cmd
                self.lock.release()
            while self.CommandStr!="":
                time.sleep(0.1)            
                

CommandManager=CommandManager()